﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using FooFun.Web.Utils;

namespace FAQFrameworks
{
    public class AuthenticationUtil
    {
        //const string hashKey = "&*()_+YUIOP|?><QWERRT~!@#$%^";
        const string hashKey = "zhang3";
        public static Guid MakeHash(Guid newGuid, string password)
        {
            byte[] pwdBytes = Encoding.UTF8.GetBytes(password);
            byte[] encodeBytes = newGuid.ToByteArray();
            byte[] encodeBytes1 = Encoding.UTF8.GetBytes(hashKey);

            int length
                = Math.Max(
                Math.Max(pwdBytes.Length, encodeBytes.Length),
                encodeBytes1.Length);

            byte[] result = new byte[length];

            for (int i = 0; i < length; i++)
            {

                byte x = 0xff;
                if (i < pwdBytes.Length)
                {
                    x = pwdBytes[i];
                }

                byte y = 0xff;
                if (i < encodeBytes.Length)
                {
                    y = encodeBytes[i];
                }

                byte z = 0xff;
                if (i < encodeBytes1.Length)
                {
                    z = encodeBytes1[i];
                }

                byte r = (byte)(x ^ y ^ z);

                result[i] = r;
            }

            MD5 md5 = MD5.Create();

            byte[] bytes = md5.ComputeHash(result);

            Guid guid = new Guid(bytes);

            return guid;
        }

        public static Guid MakeMD5Hash(Guid newGuid, string password)
        {
            byte[] pwdBytes = Encoding.UTF8.GetBytes(password);
            byte[] encodeBytes = newGuid.ToByteArray();

            int length
                = Math.Max(pwdBytes.Length, encodeBytes.Length);

            byte[] result = new byte[length];

            for (int i = 0; i < length; i++)
            {

                byte x = 0xff;
                if (i < pwdBytes.Length)
                {
                    x = pwdBytes[i];
                }

                byte y = 0xff;
                if (i < encodeBytes.Length)
                {
                    y = encodeBytes[i];
                }

                byte r = (byte)(x ^ y);

                result[i] = r;
            }

            MD5 md5 = MD5.Create();

            byte[] bytes = md5.ComputeHash(result);

            Guid guid = new Guid(bytes);

            return guid;
        }

        public static string EncodeUserId(Guid userId)
        {
            return SiteUrlsProvider.GetGuidUrl(userId);
        }

        public static Guid DecodeUserId(string str)
        {
            Guid guid = SiteUrlsProvider.GetGuidFromUrl(str);

            return guid;
        }
    }
}
